Page({
  data: {
    courseTypes: [],
    selectedTypeId: null,
    currentType: 'all',
    allClassArr: [],
    shaixuanArr: [
      { text: '综合排序', type: 'all' },
      { text: '人气', type: 'hotCourses' },
      { text: '好评率', type: 'goodCourses' },
      { text: '价格', type: 'price' },
      { text: '价格区间', type: 'priceRange' }
    ],
    priceRanges: [
      { min: 0, max: 100, text: '0-100元' },
      { min: 100, max: 200, text: '100-200元' },
      { min: 200, max: 500, text: '200-500元' },
      { min: 500, text: '500元以上' }
    ],
    pageNo: 1,
    pageSize: 6,
    hasMore: true,
    isLoading: false,
    selectedSx: 0,
    selectedPriceRange: null,
    showPriceRanges: false
  },

  loadCourseTypes() {
    wx.request({
      url: 'http://120.26.112.194:80/api/admin/fm/courseType',
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 200) {
          const types = res.data.data;
          const allTypes = [
            { courseTypeId: null, courseTypeName: '全部' },
            ...types
          ];
          this.setData({
            courseTypes: allTypes,
            currentType: null
          }, () => {
            this.loadCourseList();
          });
        }
      }
    });
  },

  sendIndex(e) {
    const index = e.currentTarget.dataset.index;
    const type = this.data.shaixuanArr[index].type;
    
    if (type === 'priceRange') {
      this.setData({
        showPriceRanges: true,
        selectedSx: index
      });
      return;
    }
    
    if (index === this.data.selectedSx) {
      return;
    }
    
    this.setData({
      selectedSx: index,
      currentType: type,
      pageNo: 1
    }, () => {
      this.loadCourseList();
    });
  },

  selectPriceRange(e) {
    const index = e.currentTarget.dataset.index;
    const range = this.data.priceRanges[index];
    
    this.setData({
      showPriceRanges: false,
      selectedPriceRange: index,
      currentType: 'priceRange',
      minPrice: range.min,
      maxPrice: range.max,
      pageNo: 1
    }, () => {
      this.loadCourseList();
    });
  },

  selectType(e) {
    const typeId = e.currentTarget.dataset.type;
    
    if (this.data.selectedTypeId === typeId) {
      return;
    }
    
    this.setData({
      selectedTypeId: typeId,
      pageNo: 1,
      allClassArr: []
    }, () => {
      this.loadCourseList();
    });
  },

  loadCourseList() {
    if (this.data.isLoading) return;
    
    this.setData({ isLoading: true });
    wx.showLoading({ title: '加载中...' });
    
    const params = {
      page: this.data.pageNo,
      pageSize: this.data.pageSize,
      type: this.data.currentType === null ? 'all' : this.data.currentType,
    };
    
    if (this.data.selectedTypeId !== null) {
      params.typeId = this.data.selectedTypeId;
    }
    
    if (this.data.currentType === 'priceRange') {
      params.minPrice = this.data.minPrice;
      if (this.data.minPrice !== 500) {
        params.maxPrice = this.data.maxPrice;
      }
    }
    
    wx.request({
      url: 'http://120.26.112.194:80/api/admin/courses/type',
      method: 'GET',
      data: params,
      success:(res)=>{
        if(res.data && res.data.code === 200) {
          const list = res.data.data.list || [];
          const hasNextPage = res.data.data.hasNextPage;
          
          const formattedList = list.map(item => ({
            ...item,
            actualPrice: item.discount ? 
              (parseFloat(item.originalPrice) * parseFloat(item.discount)).toFixed(2) : 
              parseFloat(item.originalPrice).toFixed(2),
            studyCount: item.studyCount || 0,
            reviewCount: item.reviewCount || 0,
            favoriteCount: item.favoriteCount || 0,
            purchaseVolume: item.purchaseVolume || 0
          }));
          
          this.setData({
            allClassArr: this.data.pageNo === 1 ? formattedList : [...this.data.allClassArr, ...formattedList],
            hasMore: hasNextPage
          });
        }
      },
      complete: () => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        this.setData({ isLoading: false });
      }
    });
  },

  onLoad() {
    this.loadCourseTypes();
  },

  onPullDownRefresh() {
    this.setData({
      pageNo: 1,
      hasMore: true
    }, () => {
      this.loadCourseList();
    });
  },

  onReachBottom() {
    if (!this.data.hasMore || this.data.isLoading) return;
    
    this.setData({
      pageNo: this.data.pageNo + 1
    }, () => {
      this.loadCourseList();
    });
  },

  closePriceRanges() {
    this.setData({
      showPriceRanges: false
    });
  },

  collectCourse(e) {
    const courseId = e.currentTarget.dataset.id;
    const userId = wx.getStorageSync('userId');
    
    if (!userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    wx.request({
      url: 'http://120.26.112.194:80/api/admin/courses/collect',
      method: 'POST',
      data: {
        userId: userId,
        courseId: courseId
      },
      success: (res) => {
        if (res.data.code === 200) {
          const allClassArr = this.data.allClassArr.map(item => {
            if (item.courseId === courseId) {
              return { ...item, isCollected: true };
            }
            return item;
          });
          
          this.setData({ allClassArr });
          
          wx.showToast({
            title: '收藏成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.msg || '收藏失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '收藏失败',
          icon: 'none'
        });
      }
    });
  }
}); 